<?php
///
namespace lxsphp\Store\Redis;

///
use lxsphp\App;

/**
 * 存储类 - Redis
 *
 * @version $Id: Redis.php 191 2014-07-17 10:14:35Z linsir123 $
 * @package lxsphp\Store\Redis
 */
class Redis
{
	/**
	 * 配置
	 *
	 * @var array
	 */
	public $conf;

	/**
	 * 实例
	 *
	 * @var \Redis
	 */
	private $_redis;

	/**
	 * @var bool
	 */
	private $_flag = true;

	/**
	 * 构造函数
	 *
	 * @param array $conf 配置
	 *
	 * @throws \Exception
	 */
	public function __construct($conf)
	{
		///
		$this->conf = $conf;

		///
		$this->_connect();
	}

	/**
	 * 析构函数
	 */
	function __destruct()
	{
		///
		if ($this->_flag && ! empty($this->_redis))
			$this->_redis->close();
	}

	/**
	 * 重载方法(具体需要查看提供的API)
	 *
	 * @param string $method 方法名
	 * @param array $params 参数列表
	 *
	 * @throws \Exception
	 * @return mixed
	 */
	public function __call($method, $params = array())
	{
		///
		App::$I->getDebugger()->timerStart();

		///
		if (! method_exists($this->_redis, $method))
			App::$I->getHandler()->panic(sprintf("[Redis] Unknown method '%s'", $method));

		$date = call_user_func_array(array($this->_redis, $method), $params);

		///
		App::$I->getDebugger()->log($method . json_encode($params));

		///
		return $date;
	}

	/**
	 * 连接
	 *
	 * @throws \Exception
	 */
	private function _connect()
	{
		///
		App::$I->getDebugger()->timerStart();

		///
		try {
			$this->_redis = new \Redis();
			$this->_redis->connect($this->conf[0], $this->conf[1], 5);
			$this->_redis->select($this->conf[2]);
		} catch (\Exception $e) {
			///
			$this->_flag = false;
		}

		///
		App::$I->getDebugger()->log(sprintf("[Redis] - Init: %s:%s[%s]",
			$this->conf[0], $this->conf[1], $this->conf[2]));

		///
		if (isset($e))
			App::$I->getHandler()->panic($e);
	}
}
